#include "CameraClient_Acceptor.h"
#include "CameraClient_Handler.h"
#include "StatusReport.h"
#include "CameraManager.h"



int CCameraClient_Acceptor::open (u_short serverport) 
{
	ACE_INET_Addr local_addr;
	if (local_addr.set(serverport) == -1)
		ACE_ERROR_RETURN ( (LM_ERROR, "set local address at %d %p\n", 
		serverport, "failed"), -1 );

	DWORD size = 32*1024;
	BOOL bNoDelay = 1;

	if (acceptor_.open (local_addr) == -1) 
		ACE_ERROR_RETURN ( (LM_ERROR, "listen TCP local address at %d %p\n", 
		serverport, "failed"), -1 );

	if (acceptor_.set_option(SOL_SOCKET, SO_RCVBUF, (void *)&size, sizeof(DWORD)) == -1
		||
		acceptor_.set_option(SOL_SOCKET, SO_SNDBUF, (void *)&size, sizeof(DWORD)) == -1
		)
	{
		int err = ACE_OS::last_error();
		ACE_DEBUG ( (LM_ERROR, "set option of camera tcp sock %p(%d)\n",
			"failed", err) );
	}
	ACE_DEBUG ( ( LM_DEBUG, "Begin to listen TCP port %d ...\n", serverport));

	//acceptor_.enable(ACE_NONBLOCK)

	return reactor()->register_handler(this, ACE_Event_Handler::ACCEPT_MASK);
}

int CCameraClient_Acceptor::handle_input (ACE_HANDLE) 
{

	CCameraClient_Handler *pHandler = new CCameraClient_Handler(reactor());
	ACE_ASSERT(pHandler!=NULL);
	ACE_INET_Addr l_addr;


	if (acceptor_.accept (pHandler->peer (), 
		&(l_addr), &ACE_Time_Value(0, 1000)) == -1) 
	{
		ACE_DEBUG ( (LM_ERROR, "accept one camera %p\n", "failed"));
		delete pHandler;
		return -1;
	} 
	else 
	{
		pHandler->addr() = l_addr;

		ACE_DEBUG ( ( LM_DEBUG, "tcp camera %s:%d connect in\n", 
			l_addr.get_host_addr(), l_addr.get_port_number() ) );

// 		if (pHandler->open() == -1) {
// 			ACE_DEBUG ( ( LM_DEBUG, "make camera tcp connection to %s:%d %p(%d)\n",
// 				pHandler->addr().get_host_addr(), 
// 				pHandler->addr().get_port_number(), 
// 				"failed", 
// 				ACE_OS::last_error()) );
// //			pHandler->handle_close();
// 			return 0;
// 		}

		if (ACE_Thread_Manager::instance()->spawn(
			(ACE_THR_FUNC)pHandler->run_svc,
			(void *)pHandler,THR_DETACHED)  == -1) 
		{
			if (NULL!=pHandler) {
				delete pHandler;
				pHandler=NULL;
			}
			return 0;
		}


		CameraManager::instance()->base_mutex.acquire();
		CameraManager::instance()->tcpcamera_List.push_back(pHandler);
		CameraManager::instance()->base_mutex.release();

	}
	return 0;
}

int CCameraClient_Acceptor::handle_close (ACE_HANDLE, ACE_Reactor_Mask) 
{
	ACE_DEBUG((LM_DEBUG,"End to listen TCP.... \n"));

	acceptor_.close();
//	delete this;

	return 0; 
}
